<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>食物管理 - 健康食谱管理系统</title>
    <link href="https://lib.baomitu.com/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lib.baomitu.com/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #f8f9fa;
            width: 250px;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
        }
        main {
            margin-left: 250px;
            padding: 48px 15px 15px;
        }
        .nav-link {
            color: #333;
            padding: 0.8rem 1rem;
        }
        .nav-link:hover {
            background-color: #e9ecef;
        }
        .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .nav-link i {
            width: 20px;
            text-align: center;
            margin-right: 10px;
        }
        .table img {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 4px;
        }
        .search-box {
            margin-bottom: 20px;
        }
        .preview-image {
            max-width: 200px;
            max-height: 200px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-dark bg-dark fixed-top">
        <div class="container-fluid">
            <span class="navbar-brand">健康食谱后台管理</span>
            <div class="d-flex">
                <span class="navbar-text me-3" id="adminName"></span>
                <button class="btn btn-outline-light btn-sm" onclick="handleLogout()">退出</button>
            </div>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="sidebar-sticky">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">
                        <i class="fas fa-home"></i>仪表盘
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="users.html">
                        <i class="fas fa-users"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="recipes.html">
                        <i class="fas fa-utensils"></i>食谱管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="foods.html">
                        <i class="fas fa-apple-alt"></i>食物管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="posts.html">
                        <i class="fas fa-comments"></i>帖子管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="sports.html">
                        <i class="fas fa-running"></i>运动记录
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="diets.html">
                        <i class="fas fa-hamburger"></i>饮食记录
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main>
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="h2">食物管理</h1>
                <button class="btn btn-primary" onclick="showAddModal()">
                    <i class="fas fa-plus"></i> 添加食物
                </button>
            </div>

            <!-- 搜索框 -->
            <div class="search-box">
                <div class="input-group">
                    <input type="text" class="form-control" id="searchInput" placeholder="搜索食物名称...">
                    <button class="btn btn-outline-secondary" type="button" onclick="searchFoods()">
                        <i class="fas fa-search"></i> 搜索
                    </button>
                </div>
            </div>

            <!-- 食物列表 -->
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>图片</th>
                            <th>名称</th>
                            <th>分类</th>
                            <th>单位</th>
                            <th>热量(kcal)</th>
                            <th>蛋白质(g)</th>
                            <th>碳水(g)</th>
                            <th>脂肪(g)</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="foodList">
                        <!-- 食物列表将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </main>

    <!-- 添加/编辑食物模态框 -->
    <div class="modal fade" id="foodModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">添加食物</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="foodForm">
                        <input type="hidden" id="foodId">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">食物名称</label>
                                <input type="text" class="form-control" id="name" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">分类</label>
                                <input type="text" class="form-control" id="category" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">单位</label>
                                <input type="text" class="form-control" id="unit" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">图片</label>
                                <input type="file" class="form-control" id="image" accept="image/*">
                                <input type="hidden" id="imageUrl">
                                <img id="imagePreview" class="preview-image" style="display: none;">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">热量(kcal)</label>
                                <input type="number" class="form-control" id="calories" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">蛋白质(g)</label>
                                <input type="number" class="form-control" id="protein" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">碳水化合物(g)</label>
                                <input type="number" class="form-control" id="carbs" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">脂肪(g)</label>
                                <input type="number" class="form-control" id="fat" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">膳食纤维(g)</label>
                                <input type="number" class="form-control" id="fiber">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">糖(g)</label>
                                <input type="number" class="form-control" id="sugar">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="handleSubmit()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://lib.baomitu.com/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;
        let foodModal;
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            showAdminName();
            loadFoods();
            
            // 初始化模态框
            foodModal = new bootstrap.Modal(document.getElementById('foodModal'));
            
            // 图片预览
            document.getElementById('image').addEventListener('change', handleImagePreview);
        });

        // 显示管理员名称
        function showAdminName() {
            try {
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                document.getElementById('adminName').textContent = adminUser.nickname || adminUser.username || '';
            } catch (error) {
                console.error('显示管理员名称失败:', error);
            }
        }

        // 处理退出登录
        function handleLogout() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            window.location.href = '/admin/login.html';
        }

        // 加载食物列表
        async function loadFoods(page = 1) {
            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    window.location.href = '/admin/login.html';
                    return;
                }

                const searchQuery = document.getElementById('searchInput').value;
                const response = await fetch(`/api/admin/foods?page=${page}&limit=${pageSize}&search=${searchQuery}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('加载食物列表失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    renderFoodList(result.data.foods);
                    renderPagination(result.data.total);
                }
            } catch (error) {
                console.error('加载食物列表失败:', error);
                alert('加载食物列表失败');
            }
        }

        // 渲染食物列表
        function renderFoodList(foods) {
            const tbody = document.getElementById('foodList');
            tbody.innerHTML = foods.map(food => `
                <tr>
                    <td>
                        <img src="${food.image || '/images/default-food.png'}" 
                             alt="${food.name}"
                            >
                    </td>
                    <td>${food.name}</td>
                    <td>${food.category}</td>
                    <td>${food.unit}</td>
                    <td>${food.calories}</td>
                    <td>${food.protein}</td>
                    <td>${food.carbs}</td>
                    <td>${food.fat}</td>
                    <td>
                        <button class="btn btn-sm btn-primary me-2" onclick="showEditModal(${JSON.stringify(food).replace(/"/g, '&quot;')})">
                            编辑
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="handleDelete(${food.id})">
                            删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 渲染分页
        function renderPagination(total) {
            totalPages = Math.ceil(total / pageSize);
            const pagination = document.getElementById('pagination');
            
            let html = `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>
                </li>
            `;
            
            for (let i = 1; i <= totalPages; i++) {
                html += `
                    <li class="page-item ${currentPage === i ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                    </li>
                `;
            }
            
            html += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>
                </li>
            `;
            
            pagination.innerHTML = html;
        }

        // 切换页面
        function changePage(page) {
            if (page < 1 || page > totalPages) return;
            currentPage = page;
            loadFoods(page);
        }

        // 搜索食物
        function searchFoods() {
            currentPage = 1;
            loadFoods(1);
        }

        // 显示添加模态框
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加食物';
            document.getElementById('foodId').value = '';
            document.getElementById('foodForm').reset();
            document.getElementById('imagePreview').style.display = 'none';
            document.getElementById('imageUrl').value = '';
            foodModal.show();
        }

        // 显示编辑模态框
        function showEditModal(food) {
            document.getElementById('modalTitle').textContent = '编辑食物';
            document.getElementById('foodId').value = food.id;
            document.getElementById('name').value = food.name;
            document.getElementById('category').value = food.category;
            document.getElementById('unit').value = food.unit;
            document.getElementById('calories').value = food.calories;
            document.getElementById('protein').value = food.protein;
            document.getElementById('carbs').value = food.carbs;
            document.getElementById('fat').value = food.fat;
            document.getElementById('fiber').value = food.fiber || '';
            document.getElementById('sugar').value = food.sugar || '';
            document.getElementById('imageUrl').value = food.image || '';
            
            if (food.image) {
                document.getElementById('imagePreview').src = food.image;
                document.getElementById('imagePreview').style.display = 'block';
            } else {
                document.getElementById('imagePreview').style.display = 'none';
            }
            
            foodModal.show();
        }

        // 处理图片预览
        async function handleImagePreview(e) {
            const file = e.target.files[0];
            if (file) {
                try {
                    const token = localStorage.getItem('adminToken');
                    if (!token) {
                        throw new Error('请先登录');
                    }

                    const formData = new FormData();
                    formData.append('file', file);

                    const response = await fetch('/api/upload', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        },
                        body: formData
                    });

                    if (!response.ok) {
                        throw new Error('上传图片失败');
                    }

                    const result = await response.json();
                    if (result.code === 0 && result.data && result.data.url) {
                        document.getElementById('imagePreview').src = result.data.url;
                        document.getElementById('imagePreview').style.display = 'block';
                        document.getElementById('imageUrl').value = result.data.url;
                    } else {
                        throw new Error(result.message || '上传失败');
                    }
                } catch (error) {
                    console.error('上传图片失败:', error);
                    alert(error.message || '上传失败');
                }
            }
        }

        // 处理表单提交
        async function handleSubmit() {
            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    throw new Error('请先登录');
                }

                const foodId = document.getElementById('foodId').value;
                const foodData = {
                    name: document.getElementById('name').value,
                    category: document.getElementById('category').value,
                    unit: document.getElementById('unit').value,
                    image: document.getElementById('imageUrl').value,
                    calories: parseFloat(document.getElementById('calories').value),
                    protein: parseFloat(document.getElementById('protein').value),
                    carbs: parseFloat(document.getElementById('carbs').value),
                    fat: parseFloat(document.getElementById('fat').value),
                    fiber: parseFloat(document.getElementById('fiber').value) || 0,
                    sugar: parseFloat(document.getElementById('sugar').value) || 0
                };

                const url = foodId ? 
                    `/api/admin/foods/${foodId}` : 
                    '/api/admin/foods';
                    
                const response = await fetch(url, {
                    method: foodId ? 'PUT' : 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(foodData)
                });

                if (!response.ok) {
                    throw new Error('保存食物失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    alert('保存成功');
                    foodModal.hide();
                    loadFoods(currentPage);
                } else {
                    throw new Error(result.message || '保存失败');
                }
            } catch (error) {
                console.error('保存食物失败:', error);
                alert(error.message || '保存失败');
            }
        }

        // 处理删除
        async function handleDelete(id) {
            if (!confirm('确定要删除这个食物吗？')) {
                return;
            }

            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    throw new Error('请先登录');
                }

                const response = await fetch(`/api/admin/foods/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('删除食物失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    alert('删除成功');
                    loadFoods(currentPage);
                } else {
                    throw new Error(result.message || '删除失败');
                }
            } catch (error) {
                console.error('删除食物失败:', error);
                alert(error.message || '删除失败');
            }
        }
    </script>
</body>
</html> 